package com.example.study.page.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import com.example.study.databinding.FragmentImageBinding

class ImageFragment : Fragment() {
    private lateinit var binding: FragmentImageBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentImageBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.getInt(ARG_IMG_RES)?.let {
            binding.imgView.setImageResource(it)
            binding.textView.text = it.toString()
        }
    }


    companion object {
        private const val ARG_IMG_RES = "image_res"
        private val cache = HashMap<String, ImageFragment>()

        fun newInstance(@DrawableRes imageRes: Int): ImageFragment {
            val key = imageRes.toString()
            return cache.getOrElse(key) {
                val args = Bundle().apply {
                    putInt(ARG_IMG_RES, imageRes)
                }
                ImageFragment().apply {
                    arguments = args
                }.also {
                    //cache[key] = it  //FragmentStateAdapter#createFragment不支持缓存，可以使用recyclerViewAdapter
                }
            }

        }
    }

}